import React, { useCallback, useRef, useState } from 'react';
import { Button, Drawer, Form, Input, message, Popconfirm, Select, Space, Switch } from 'antd';
import { ProTable, ProColumns } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { queryTag, addTag, editTag,deleteTag } from '@/services/ant-design-pro/news';
import type { ActionType } from '@ant-design/pro-components';

const { Option } = Select;

const AgreementList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [currentRecord, setCurrentRecord] = useState<any | undefined>(undefined);
  const [form] = Form.useForm();
  

  const { run: createRun } = useRequest(addTag, {
    manual: true,
    onSuccess: () => {
      actionRef.current?.reload();
      message.success('创建成功');
    },
    onError: () => {
      message.error('创建失败，请重试');
    },
  });

  const { run: updateRun } = useRequest(editTag, {
    manual: true,
    onSuccess: () => {
      actionRef.current?.reload();
      message.success('更新成功');
    },
    onError: () => {
      message.error('更新失败，请重试');
    },
  });

  const handleSave = useCallback(
    async (values: any) => {
      // 将 Switch 的值转换为 0 或 1
      values.status = values.status ? 0 : 1;
      if (currentRecord) {
        await updateRun({ ...currentRecord, ...values });
      } else {
        await createRun(values);
      }
      setDrawerVisible(false);
    },
    [currentRecord, createRun, updateRun],
  );

  const columns: ProColumns<any>[] = [
    {
      title: '标签名称',
      dataIndex: 'name',
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      ellipsis: true,
      render: (text,record) => {
        return record.status  ? '禁用' : '启用';
},
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
      ellipsis: true,
    },
    {
      title: '操作',
      width: 180,
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setCurrentRecord(record);
            form.setFieldsValue({
              ...record,
              status: record.status === 0, // 将 1 转换为 true，0 转换为 false
            });
            setDrawerVisible(true);
          }}
        >
          编辑
        </a>,
                <Popconfirm
                key="delete"
                title="确定删除该新闻吗？"
                onConfirm={() => handleRemove(record.id)}
              >
                <a>删除</a>
              </Popconfirm>,
      ],
    },
  ];


  const handleRemove = async (id) => {
    try {
      const response = await deleteTag(id);
      if (response.code === '1') {
        message.success('删除成功');
        actionRef.current?.reload();
      } else {
        message.error(response.msg);
      }
    } catch (error) {
      message.error('删除失败');
    }
  };


  return (
    <>
      <ProTable<any>
        headerTitle="标签管理"
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <Button
            key={'new'}
            type="primary"
            onClick={() => {
              setCurrentRecord(undefined);
              form.resetFields();
              setDrawerVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
        request={(params) => queryTag(params)}
        columns={columns}
      />

      <Drawer
        title={currentRecord ? '标签详情' : '添加标签'}
        width={600}
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
        footer={
          <Space>
            <Button onClick={() => setDrawerVisible(false)}>取消</Button>
            <Button
              type="primary"
              onClick={() => {
                form.validateFields().then(handleSave);
              }}
            >
              提交
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="标签名称" rules={[{ required: true }]}>
            <Input placeholder="请输入标签名称" />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true }]}
            valuePropName="checked" // 使用 checked 作为值属性
          >
            <Switch />
          </Form.Item>
        </Form>
      </Drawer>
    </>
  );
};

export default AgreementList;